彈跳視窗有很多種類似的名稱
例如:Alert、Dialog、Modal、Popup 等等,彼此各有些許的差異,在此統一以Modal來稱呼。
在網頁中,彈跳視窗有兩種作法
除了用Bootstrap原生套件做效果之外
Angular也有內件的 ng-bootstrap ,透過NgbModal 搭配NgbActiveModal模組來做出彈跳視窗元件,也是本文接下來會介紹的作法
ng-bootstrap開啟一個新的專案,並在專案中導入Bootstrap套件
> ng add @ng-bootstrap/ng-bootstrap
Bootstrap套件的Modal是透過樣板和純粹的Javascript來完成
若要使用Modal也可以自己寫
先來看看 陽春版的Modal
> ng g c modal01
修改modal01.component.html
<div class="p-3" style="border: solid 1px black">
  <div class="modal-header">
    <h5 class="modal-title flex-fill">彈跳視窗標題</h5>
  </div>
  <div class="modal-body">
    <div class="mb-5">
      <p>請確認是否繼續進行?</p>
    </div>
    <div class="d-flex flex-wrap justify-content-center">
      <div class="w-50 btn bg-info" (click)="confirm()">是</div>
      <div class="w-50 btn bg-light" (click)="deny()">否</div>
    </div>
  </div>
</div>
可以為這兩個按鈕各寫一個方法來進行處理,偵測使用者按下了哪個按鈕
修改modal01.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-modal01',
  templateUrl: './modal01.component.html',
  styleUrls: ['./modal01.component.css']
})
export class Modal01Component implements OnInit {
  constructor() { }
  ngOnInit(): void {
  }
  confirm() {
    alert('您點擊了"是"');
  }
  deny() {
    alert('您點擊了"否"');
  }
}
在需要用到此元件的地方來呼叫使用
修改app.component.html
<div class="container">
  <div class="row justify-content-center">
    <div class="col-4">
      <app-modal01></app-modal01>
    </div>
  </div>
</div>
結果畫面
